import express from 'express';
import mysql from 'mysql2/promise';
import cors from 'cors';

const app = express();
app.use(cors());

// 数据库配置
const pool = mysql.createPool({
  host: 'localhost',
  port:'3306',
  user: 'root',
  password: '123456',
  database: 'mapscreen'
});

// 获取省份数据接口
app.get('/api/provinceStats', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM provinces');
    res.json({
      code: 200,
      data: rows
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      message: '数据库查询失败'
    });
  }
});

// 添加省份数据
app.post('/api/provinces', async (req, res) => {
  try {
    const { name, employed, unemployed, rate } = req.body;
    const [result] = await pool.query(
      'INSERT INTO provinces (name, employed, unemployed, rate) VALUES (?, ?, ?, ?)',
      [name, employed, unemployed, rate]
    );
    res.json({
      code: 200,
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      message: '添加省份数据失败'
    });
  }
});

// 更新省份数据
app.put('/api/provinces/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, employed, unemployed, rate } = req.body;
    await pool.query(
      'UPDATE provinces SET name = ?, employed = ?, unemployed = ?, rate = ? WHERE id = ?',
      [name, employed, unemployed, rate, id]
    );
    res.json({
      code: 200,
      message: '更新成功'
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      message: '更新省份数据失败'
    });
  }
});

// 删除省份数据
app.delete('/api/provinces/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await pool.query('DELETE FROM provinces WHERE id = ?', [id]);
    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      message: '删除省份数据失败'
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});